package com.ruoyi.web.controller.h5.acceptance;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.dto.AcceptanceChecklistSubmitDTO;
import com.ruoyi.system.service.AcceptanceChecklistInstanceService;
import com.ruoyi.system.vo.AcceptanceChecklistInstanceVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * H5验收单控制器
 * 提供H5用户验收单查询、提交等功能
 * 
 * @author ruoyi
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/h5/acceptance/checklist")
@PreAuthorize("@userType.isH5()")
public class H5AcceptanceChecklistController extends BaseController {

    /**
     * 验收单实例服务
     */
    @Resource
    private AcceptanceChecklistInstanceService instanceService;

    /**
     * 获取验收单实例详情
     * 
     * @param instanceId 实例ID
     * @return 实例详情
     */
    @GetMapping("/{instanceId}")
    public AjaxResult detail(@PathVariable Long instanceId) {
        AcceptanceChecklistInstanceVO detail = instanceService.getInstanceDetail(instanceId);
        return AjaxResult.success(detail);
    }

    /**
     * 根据消息子项ID获取验收单实例
     * 
     * @param msgItemId 消息子项ID
     * @return 实例详情
     */
    @GetMapping("/by-msg-item/{msgItemId}")
    public AjaxResult getByMsgItemId(@PathVariable Long msgItemId) {
        AcceptanceChecklistInstanceVO detail = instanceService.getInstanceByMsgItemId(msgItemId);
        return AjaxResult.success(detail);
    }

    /**
     * 提交验收单
     * 
     * @param submitDTO 提交参数
     * @return 提交结果
     */
    @PostMapping("/submit")
    public AjaxResult submit(@Valid @RequestBody AcceptanceChecklistSubmitDTO submitDTO) {
        // 设置当前用户ID
        if (submitDTO.getH5UserId() == null) {
            submitDTO.setH5UserId(SecurityUtils.getH5LoginUser().getUserId());
        }
        
        Boolean result = instanceService.submitChecklist(submitDTO);
        return result ? AjaxResult.success() : AjaxResult.error("提交失败");
    }

    /**
     * 获取H5用户的验收单实例列表
     * 
     * @param status 状态过滤
     * @return 实例列表
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam(required = false) String status) {
        Long h5UserId = SecurityUtils.getH5LoginUser().getUserId();
        List<AcceptanceChecklistInstanceVO> list = instanceService.getInstancesByH5UserId(h5UserId, status);
        return AjaxResult.success(list);
    }
}

